<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>地址管理</p>
    </header>

    <!-- 地址列表部分 -->
    <ul class="address-list">
      <li v-for="item in deliveryAddressArr" :key="item.daId">
        <div class="address-item" @click="setDeliveryAddress(item)">
          <!-- 标签和地址 -->
          <div class="address-info">
            <div class="tag">常用</div>
            <div class="address">{{item.address}}</div>
          </div>
          
          <!-- 联系人信息 -->
          <div class="contact-info">
            <span class="name">{{item.contactName}}</span>
            <span class="gender">{{item.contactSex == 1 ? '(先生)' : '(女士)'}}</span>
            <span class="phone">{{item.contactTel}}</span>
          </div>
        </div>

        <!-- 编辑按钮 -->
        <div class="edit-area">
          <i class="fa fa-edit" @click.stop="editUserAddress(item.daId)"></i>
          <i class="fa fa-trash" @click.stop="removeUserAddress(item.daId)"></i>
        </div>
      </li>
    </ul>

    <!-- 新增地址按钮 -->
    <div class="add-address" @click="toAddUserAddress">
      <span>+ 新增地址</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getCurrentInstance } from 'vue'
import Footer from './Footer.vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

const businessId = ref(route.query.businessId)
const user = ref({})
const deliveryAddressArr = ref([])

onMounted(() => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  user.value = proxy.$getSessionStorage('user')
  if (!user.value) {
    ElMessage.warning('用户信息已失效，请重新登录')
    router.push('/login')
    return
  }

  listDeliveryAddressByUserId()
})

const listDeliveryAddressByUserId = () => {
  request({
    url: '/DeliveryAddressController/listDeliveryAddressByUserId',
    method: 'get',
    params: {
      userId: user.value.userId
    }
  }).then(response => {
    deliveryAddressArr.value = response.data
  }).catch(error => {
    console.error(error)
    ElMessage.error('获取地址列表失败')
  })
}

const setDeliveryAddress = (deliveryAddress) => {
  proxy.$setLocalStorage(user.value.userId, deliveryAddress)
  router.push({
    path: '/orders',
    query: { businessId: businessId.value }
  })
}

const toAddUserAddress = () => {
  router.push({
    path: '/addUserAddress',
    query: { businessId: businessId.value }
  })
}

const editUserAddress = (daId) => {
  router.push({
    path: '/editUserAddress',
    query: {
      businessId: businessId.value,
      daId: daId
    }
  })
}

const removeUserAddress = async (daId) => {
  try {
    const token = sessionStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const response = await request({
      url: '/DeliveryAddressController/removeDeliveryAddress',
      method: 'delete',
      headers: {
        'Authorization': token
      },
      params: {
        daId: daId
      }
    })

    if (response.data === 1) {
      ElMessage.success('删除成功')
      let deliveryAddress = proxy.$getLocalStorage(user.value.userId)
      if (deliveryAddress != null && deliveryAddress.daId == daId) {
        proxy.$removeLocalStorage(user.value.userId)
      }
      listDeliveryAddressByUserId()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('删除地址错误:', error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('删除地址失败')
    }
  }
}
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

header {
  width: 100%;
  height: 44px;
  background: #fff;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #333;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.address-list {
  margin-top: 44px;
  padding: 12px;
}

.address-list li {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  position: relative;
}

.address-item {
  padding: 15px;
  cursor: pointer;
}

.address-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.tag {
  font-size: 12px;
  color: #ff6b01;
  background: #fff5e6;
  padding: 2px 6px;
  border-radius: 2px;
  margin-right: 8px;
}

.address {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.contact-info {
  font-size: 13px;
  color: #999;
  display: flex;
  align-items: center;
}

.contact-info .name {
  margin-right: 4px;
}

.contact-info .gender {
  margin-right: 8px;
}

.contact-info .phone {
  color: #666;
}

.edit-area {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 15px;
}

.edit-area i {
  font-size: 16px;
  color: #999;
  cursor: pointer;
  padding: 5px;
}

.edit-area i.fa-trash {
  color: #ff4d4f;
}

.edit-area i:active {
  opacity: 0.7;
}

.add-address {
  position: fixed;
  bottom: 20px;
  left: 15px;
  right: 15px;
  height: 44px;
  background: #0097FF;
  color: #fff;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 22px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,151,255,0.3);
}

/* 添加点击效果 */
.address-item:active {
  background: #f9f9f9;
}

.add-address:active {
  opacity: 0.9;
}

.edit-btn:active {
  opacity: 0.7;
}
</style>